package com.info3k.client.commands.category;

import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Label;
import com.info3k.client.Info3K;
import com.info3k.client.components.GlassDialogBox;
import com.info3k.client.components.InfoWindow;
import com.info3k.client.components.validators.TextBoxValidator;
import com.info3k.client.domain.Category;
import com.info3k.client.enums.TabTypes;


public class NewCategoryCommand extends GlassDialogBox implements Command {

	private TextBoxValidator code = new TextBoxValidator();
	private TextBoxValidator name = new TextBoxValidator();
	
	private Button addButton = new Button(Info3K.msgs.add());
	
	private Info3K info3k;
	
	public NewCategoryCommand(Info3K info){
		this.info3k = info;
		
		addButton.addClickHandler(new ClickHandler(){
			public void onClick(ClickEvent event) {
				if(name!=null && code.isValid()){
					Category cat = new Category();
					cat.setCode(code.getText());
					cat.setName(name.getText());
					Info3K.loader.setVisible(true);
					Info3K.infoService.addCategory(cat, new AsyncCallback<Void>(){
						public void onFailure(Throwable caught) {
							Info3K.loader.setVisible(false);
							InfoWindow.showMessage(Info3K.msgs.error(), caught.getMessage());
						}
	
						public void onSuccess(Void result) {
							Info3K.loader.setVisible(false);
							InfoWindow.showMessage(Info3K.msgs.ok(), Info3K.msgs.categoryAddedSuccessfully());
							info3k.getTabManager().refresh(TabTypes.CATEGORIES_LEFT);
							hide();
						}
					});
				} else InfoWindow.showMessage(Info3K.msgs.error(), Info3K.msgs.pleaseFillAllFields());
			}
		});
		
		setText(Info3K.msgs.new1() + " " + Info3K.msgs.category());		
		name.setWidth("300px");
		code.setWidth("300px");
		
		final Label lblName = new Label(Info3K.msgs.name());
		final Label lblCode = new Label(Info3K.msgs.code());
				
		content.add(lblName);
		content.add(name);
		content.add(lblCode);
		content.add(code);
		
		code.addChangeHandler(new ChangeHandler(){
			public void onChange(ChangeEvent event) {
				code.setValid(code.getText().length()>0);
			}
		});
		
		name.addChangeHandler(new ChangeHandler(){
			public void onChange(ChangeEvent event) {
				name.setValid(name.getText().length()>0);
			}
		});
		
		footer.add(addButton);
		addButton.getElement().getStyle().setProperty("margin", "0 10px 0 0");
		footer.add(closeButton);
	}

	public void execute() {
		center();
	}
}